import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import {Message} from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
//import Mock from './mock'
//Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
import {hasPermission} from './vuex/modules/permission'

Vue.use(ElementUI);
Vue.use(VueRouter);
Vue.use(Vuex);

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
    routes
});

router.beforeEach((to, from, next) => {
    if (to.path === '/login') {
        localStorage.removeItem('Authorization');
        next()
    } else {
        let token = localStorage.getItem('Authorization');
        let user = sessionStorage.getItem('user');
        if (user) {
            user = JSON.parse(user);
        }
        if (token === 'null' || token === '' || user == null) {
            next({path: '/login'})
        } else {
            console.log('store.getters.perms.length:', store.getters.perms.length);
            if (store.getters.perms.length === 0) {
                store.dispatch('GetUserInfo').then(res => {
                    const perms = res.data.data.perms;
                    store.dispatch('GenerateRoutes', {perms}).then(() => {
                        // 根据perms权限生成可访问的路由表
                        router.addRoutes(store.getters.addRouters);
                        // 动态添加可访问路由表
                        next({...to, replace: true}) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    })
                }).catch((err) => {
                    Message.error(err || 'Verification failed, please login again');
                    next({path: '/login'})
                })
            } else {
                console.log('to.path', to.path);
                if (hasPermission(store.getters.perms, to.meta.perms)) {
                    next()
                } else {
                    next({path: '/401', replace: true, query: {noGoBack: true}})
                }
                // 可删 ↑
            }
        }
    }
});

window.vm = new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
});

